package com.example.server.config;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;
import java.util.regex.Pattern;

@Component
public class InstantConverter implements Converter<String, Instant> {

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    static final Pattern TIMESTAMP_PATTERN = Pattern.compile("\\d{13}");

    @Override
    public Instant convert(String source) {
        String dateString = source.trim();
        if (!dateString.isEmpty()) {
            Date pareDate = null;
            if (TIMESTAMP_PATTERN.matcher(dateString).matches()) {
                pareDate = new Date(new Long(dateString));
            } else {
                try {
                    pareDate = format.parse(dateString);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (null != pareDate) {
                return pareDate.toInstant();
            }
        }
        return null;
    }

}